package com.msec.permission.demo;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;

import com.alibaba.fastjson.JSON;

import java.util.HashMap;

public class RequestHelper {

    private static final String TAG = "permission_demo_logger";

    public static void requestPermission(PermissionRequest permissionRequest) {
        requestPermission(ActivityLifeCycleHandler.INSTANCE().currentActivity(), permissionRequest.getPermissionName(), permissionRequest.getCallBack());
    }

    public static void requestPermission(Activity activity, PermissionRequest permissionRequest) {
        requestPermission(activity, permissionRequest.getPermissionName(), permissionRequest.getCallBack());
    }

    public static void requestPermission(String[] permissions, @NonNull PermissionCallBack callBack) {
        requestPermission(ActivityLifeCycleHandler.INSTANCE().currentActivity(), permissions, callBack);
    }

    public static void requestPermission(Activity activity, String[] permissions, @NonNull PermissionCallBack callBack) {

        if (activity != null) {
            Intent intent = new Intent(activity, PermissionRequestActivity.class);
            intent.putExtra("permissions", permissions);
            Bundle bundle = new Bundle();
            bundle.putParcelable("callBack", callBack);
            intent.putExtras(bundle);
            activity.startActivity(intent);
        } else {
            PermissionRequest permissionRequest = new PermissionRequest(PermissionAccessStatus.DENIED, permissions, callBack);
            ActivityLifeCycleHandler.INSTANCE().permissionRequestList.add(permissionRequest);
            Log.d(TAG, "Acitivty 还未准备好，待首UI界面初始化完毕，则开始申请权限:" + JSON.toJSONString(permissions));
        }
    }


    public static  HashMap<String, Integer> getDefinedPermission(Context context) throws PackageManager.NameNotFoundException {
        HashMap<String, Integer> map = new HashMap<>();
        PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS);
        if (pi.requestedPermissions != null) {
            for (String p : pi.requestedPermissions) {
                map.put(p, PermissionAccessStatus.DENIED);
            }
        }
        return map;
    }
}
